package com.ndp.fb.util;

import com.ndp.fb.constant.CommonConstants;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by hunk.qin on 2016/2/15.
 */
public class ArrayUtil {

    /**
     * 将InputStream转为byte数组.
     *
     * @param inStream 待转换的InputStream
     * @return 转换后的byte数组
     * @throws IOException 异常
     */
   public static byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }

    public static byte[] getByteByUrl(String urlstr) {
        byte[] bytes = null;
        InputStream is = null;
        try {
            URL url = new URL(urlstr);
            URLConnection con = url.openConnection();
            con.setReadTimeout(CommonConstants.HTTP_READ_TIME_OUT);
            con.setConnectTimeout(CommonConstants.HTTP_CONNECTION_TIME_OUT);
            is = con.getInputStream();
            bytes = ArrayUtil.input2byte(is);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }

}
